/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * https://lxqt.org
 *
 * Copyright: 2015 LXQt team
 * Authors:
 *  Balázs Béla <balazsbela[at]gmail.com>
 *  Paulo Lieuthier <paulolieuthier@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */
#include "statusnotiferscrollarea.h"
#include <QGuiApplication>
#include <QScreen>
#define CONFIG_FILE_BACKUP     "/usr/share/ukui/panel.conf"

StatusNotiferScrollArea::StatusNotiferScrollArea(IUKUIPanelPlugin *plugin, QWidget *parent)
    :m_plugin(plugin),
     m_parent(parent)
{
    //检查配置文件是否完整
    QSettings backup_qsettings(CONFIG_FILE_BACKUP,QSettings::IniFormat);
    QStringList showAppBackup = backup_qsettings.value("statusnotifier/showApp").toStringList();
    QStringList hideAppBackup = backup_qsettings.value("statusnotifier/hideApp").toStringList();
    QString alignmentBackup = backup_qsettings.value("statusnotifier/alignment").toString();
    PluginSettings *settings=m_plugin->settings();  // ~/.config/ukui/panel.conf
    QStringList allkeys = settings->allKeys();
    if(!allkeys.contains("showApp")) {
        settings->setValue("showApp",showAppBackup);
    }
    if(!allkeys.contains("hideApp")) {
        settings->setValue("hideApp",hideAppBackup);
    }
    if(!allkeys.contains("alignment")) {
        settings->setValue("alignment",alignmentBackup);
    }

    //监听托盘应用注册
    m_watcher = new StatusNotifierWatcher;
    connect(m_watcher, &StatusNotifierWatcher::StatusNotifierItemRegistered,
            this, &StatusNotiferScrollArea::itemAdded);
    connect(m_watcher, &StatusNotifierWatcher::StatusNotifierItemUnregistered,
            this, &StatusNotiferScrollArea::itemRemoved);

    //设置滚动区域属性
    this->setWidgetResizable(true);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setProperty("drawScrollBarGroove",false);
    this->verticalScrollBar()->setProperty("drawScrollBarGroove",false);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->verticalScrollBar()->setVisible(false);
    this->setFrameShape(QFrame::NoFrame);
    this->setAlignment(Qt::AlignRight);
    this->setContentsMargins(0,0,0,0);
    //滚动区域背景透明
    QPalette pal = this->palette();
    pal.setBrush(QPalette::Window, QColor(Qt::transparent));
    this->setPalette(pal);

    //托盘窗口和布局
    m_statusNotifierWidget = new QWidget(this);
    this->setWidget(m_statusNotifierWidget);

    m_arrowBtn = new StatusNotifierStorageArrow(m_plugin, m_statusNotifierWidget);
    connect(m_arrowBtn,SIGNAL(addButton(QString)),this,SLOT(btnAddButton(QString)));

    m_layout = new UKUi::GridLayout(m_statusNotifierWidget);
    m_layout->setDirection(UKUi::GridLayout::LeftToRight);
    m_statusNotifierWidget->setLayout(m_layout);
    m_layout->addWidget(m_arrowBtn);

    //监听托盘图标隐藏
    const QByteArray id(UKUI_PANEL_SETTINGS);
    if(QGSettings::isSchemaInstalled(id)) {
        m_gsettings = new QGSettings(id);
        connect(m_gsettings, &QGSettings::changed, this, [=] (const QString &key){
            if(key==SHOW_STATUSNOTIFIER_BUTTON){
                exchangeHideAndShow();
            }
        });
    }
}

StatusNotiferScrollArea::~StatusNotiferScrollArea()
{
    if(m_watcher) {
        delete(m_watcher);
        m_watcher = NULL;
    }
    if(m_gsettings) {
        delete(m_gsettings);
        m_gsettings = NULL;
    }
}

void StatusNotiferScrollArea::realign()
{
    m_layout->setEnabled(false);
    IUKUIPanel *panel = m_plugin->panel();
    if (panel->isHorizontal()) {
        m_layout->setRowCount(panel->lineCount());
        m_layout->setColumnCount(0);
        m_layout->setEnabled(true);

        int widgetWidth;
        if(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool()) {
            widgetWidth = (m_allButtons.size()+1)*uint(panel->panelSize()*0.7);
        } else {
            widgetWidth = (m_allButtons.size()-m_hideButtons.size()+1)*uint(panel->panelSize()*0.7);
        }
        m_statusNotifierWidget->setFixedSize(widgetWidth, panel->panelSize());
        int margins = panel->panelSize()*0.15;
        m_statusNotifierWidget->setContentsMargins(0,margins,0,margins);

        if(widgetWidth > QGuiApplication::primaryScreen()->geometry().width()/3) {
            //托盘区超过屏幕宽度1/3，超出量不到一个图标宽度的，正常显示，否则托盘显示区为屏幕宽度1/3
            if(widgetWidth-QGuiApplication::primaryScreen()->geometry().width()/3 < uint(panel->panelSize()*0.7)) {
                this->setFixedSize(widgetWidth, panel->panelSize());
            } else {
                this->setFixedSize(QGuiApplication::primaryScreen()->geometry().width()/3, panel->panelSize());
            }
        } else {
            this->setFixedSize(widgetWidth, panel->panelSize());
        }
    } else {
        m_layout->setColumnCount(panel->lineCount());
        m_layout->setRowCount(0);
        m_layout->setEnabled(true);

        int heightWidth;
        if(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool()) {
            heightWidth = (m_allButtons.size()+1)*uint(panel->panelSize()*0.7);
        } else {
            heightWidth = (m_allButtons.size()-m_hideButtons.size()+1)*uint(panel->panelSize()*0.7);
        }
        m_statusNotifierWidget->setFixedSize(panel->panelSize(), heightWidth);
        int margins = panel->panelSize()*0.15;
        m_statusNotifierWidget->setContentsMargins(margins,0,margins,0);

        if(heightWidth > QGuiApplication::primaryScreen()->geometry().height()/3) {
            this->setFixedSize(panel->panelSize(), QGuiApplication::primaryScreen()->geometry().height()/3);
        } else {
            this->setFixedSize(panel->panelSize(), heightWidth);
        }
    }
}

void StatusNotiferScrollArea::wheelEvent(QWheelEvent *event)
{
    if(this->horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
        if(event->delta() >= 0) {
            this->horizontalScrollBar()->setValue(horizontalScrollBar()->value()-40);
        } else {
            this->horizontalScrollBar()->setValue(horizontalScrollBar()->value()+40);
        }
    }
    if(this->verticalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
        if(event->delta() >= 0) {
            this->verticalScrollBar()->setValue(verticalScrollBar()->value()-40);
        } else {
            this->verticalScrollBar()->setValue(verticalScrollBar()->value()+40);
        }
    }
}

void StatusNotiferScrollArea::itemAdded(QString serviceAndPath)
{
    int slash = serviceAndPath.indexOf('/');
    QString serv = serviceAndPath.left(slash);
    QString path = serviceAndPath.mid(slash);
    StatusNotifierButton *button = new StatusNotifierButton(serv, path, m_plugin, m_statusNotifierWidget);
    m_services.insert(serviceAndPath, button);
    connect(button, SIGNAL(switchButtons(StatusNotifierButton*,StatusNotifierButton*)), this, SLOT(switchButtons(StatusNotifierButton*,StatusNotifierButton*)));
    connect(button,&StatusNotifierButton::layoutReady,this,[=](){
        if(button->mIconStatus && !button->mId.isEmpty()) {  //Icon和ID都准备好后再加入布局
            m_statusNotifierButtons.append(button);
            resetLayout();
        }
    });
}

void StatusNotiferScrollArea::itemRemoved(const QString &serviceAndPath)
{
    StatusNotifierButton *button = m_services.value(serviceAndPath, NULL);
    if (button) {
        disconnect(button,&StatusNotifierButton::layoutReady,0,0);
        m_statusNotifierButtons.removeOne(button);
        m_layout->removeWidget(button);
        if(m_showButtons.keys().contains(button->mId)){
            m_showButtons.remove(button->mId);
        }
        if(m_hideButtons.keys().contains(button->mId)){
            m_hideButtons.remove(button->mId);
        }
        m_services.remove(serviceAndPath);
        m_allButtons.remove(button->mId);
        resetLayout();
        button->deleteLater();
    }
}

void StatusNotiferScrollArea::resetLayout()
{
    QStringList show=readSettings().at(0);
    show.removeAll("");
    QStringList hide=readSettings().at(1);
    hide.removeAll("");
    for(int i=0;i<m_statusNotifierButtons.size();i++) {
        if(m_statusNotifierButtons.at(i)) {
            m_allButtons.insert(m_statusNotifierButtons.at(i)->mId,m_statusNotifierButtons.at(i));
            if((!show.contains(m_statusNotifierButtons.at(i)->mId))&&(!hide.contains(m_statusNotifierButtons.at(i)->mId))) {
                if(m_statusNotifierButtons.at(i)->mId=="") {
                    continue;
                }
                hide.append(m_statusNotifierButtons.at(i)->mId);
                qCritical()<<"config change resetLayout:id tooltoptitle:"
                        <<m_statusNotifierButtons.at(i)->mId
                        <<m_statusNotifierButtons.at(i)->m_toolTipTitle;
                saveSettings("",m_statusNotifierButtons.at(i)->mId);
                continue;
            }
        }
        else {
            qDebug()<<"m_statusNotifierButtons add error   :  "<<m_statusNotifierButtons.at(i);
        }
    }
    for(int i=0;i<hide.size();i++) {
        if(!m_allButtons.value(hide.at(i))==NULL) {
            m_allButtons.value(hide.at(i))->setVisible(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool());
            m_layout->addWidget(m_allButtons.value(hide.at(i)));
            m_hideButtons.insert(hide.at(i),m_allButtons.value(hide.at(i)));
        }
    }
    m_layout->addWidget(m_arrowBtn);
    for(int i=0;i<show.size();i++) {
        if(!m_allButtons.value(show.at(i))==NULL) {
            if(m_allButtons.keys().contains(show.at(i))) {
                m_layout->addWidget(m_allButtons.value(show.at(i)));
                m_showButtons.insert(show.at(i),m_allButtons.value(show.at(i)));
            }
        }
    }
    m_layout->setEnabled(true);
    realign();
}

void StatusNotiferScrollArea::switchButtons(StatusNotifierButton *button1, StatusNotifierButton *button2)
{
    if (button1 == button2)
        return;

    int n1 = m_layout->indexOf(button1);
    int n2 = m_layout->indexOf(button2);

    int l = qMin(n1, n2);
    int m = qMax(n1, n2);

    m_layout->moveItem(l, m);
    m_layout->moveItem(m-1, l);

    if(!(m_hideButtons.keys().contains(button1->mId)&&m_hideButtons.keys().contains(button2->mId))) {
        m_hideButtons.remove(button1->mId);
    }
    if(!(m_showButtons.keys().contains(button1->mId)&&m_showButtons.keys().contains(button2->mId))) {
        m_showButtons.remove(button1->mId);
    }
    qCritical()<<"config change resetLayout:id1 tooltoptitle1:"
            <<button1->mId<<button1->m_toolTipTitle
            <<"id2 tooltoptitle2:"<<button2->mId<<button2->m_toolTipTitle;
    saveSettings(button1->mId,button2->mId);
    resetLayout();
}

void StatusNotiferScrollArea::saveSettings(QString button1,QString button2)
{
    PluginSettings *settings=m_plugin->settings();
    QStringList showApp=settings->value("showApp").toStringList();
    QStringList hideApp=settings->value("hideApp").toStringList();

    if(button2==NULL) {
        if(m_hideButtons.keys().contains(button1)) {
            m_hideButtons.remove(button1);
        }
        if(m_showButtons.keys().contains(button1)) {
            m_showButtons.remove(button1);
        }
        if(m_hideButtons.keys().isEmpty()) {
            hideApp.append(button1);
            if(showApp.contains(button1)) {
                showApp.removeAll(button1);
            }
        }
        if(m_showButtons.keys().isEmpty()) {
            showApp.append(button1);
            if(hideApp.contains(button1)) {
                hideApp.removeAll(button1);
            }
        }
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
        return;
    }

    if(button1==NULL){
        if(!button2.isNull()) {
            hideApp.append(button2);
            hideApp.removeAll("");
            settings->setValue("hideApp",hideApp);
            return;
        }
    }

    if(showApp.contains(button1)&&showApp.contains(button2)) {
        int tep=showApp.indexOf(button1);
        showApp.replace(showApp.indexOf(button2),button1);
        showApp.replace(tep,button2);
        settings->setValue("showApp",showApp);
    }

    if(showApp.contains(button1)&&hideApp.contains(button2)) {
        hideApp.insert(hideApp.indexOf(button2),button1);
        showApp.removeAll(button1);
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
    }


    if(hideApp.contains(button1)&&showApp.contains(button2)) {
        showApp.insert(showApp.indexOf(button2),button1);
        hideApp.removeAll(button1);
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
    }
    if(hideApp.contains(button1)&&hideApp.contains(button2)) {
        int tep=hideApp.indexOf(button1);
        hideApp.replace(hideApp.indexOf(button2),button1);
        hideApp.replace(tep,button2);
        settings->setValue("hideApp",hideApp);
    }
}

QList<QStringList> StatusNotiferScrollArea::readSettings()
{
    PluginSettings *settings=m_plugin->settings();
    QStringList showApp=settings->value("showApp").toStringList();
    QStringList hideApp=settings->value("hideApp").toStringList();
    QList<QStringList> list;
    list.append(showApp);
    list.append(hideApp);
    return list;
}

void StatusNotiferScrollArea::exchangeHideAndShow()
{
    QMap<QString, StatusNotifierButton*>::const_iterator i;
    for(i=m_hideButtons.constBegin();i!=m_hideButtons.constEnd();++i) {
        i.value()->setVisible(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool());
    }
}

void StatusNotiferScrollArea::btnAddButton(QString button)
{
    saveSettings(button,"");
    resetLayout();
}




